import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:hexcolor/hexcolor.dart';

import '../tools/FL_CustomLoading.dart';
import '../tools/KaL_Config.dart';
import '../tools/models/KaL_DataViewModels.dart';
// import '../tools/sqLite/EJ_myTicketEntity.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'views/EJ_ChooseNumbers.dart';
// import 'views/EJ_ChooseNumbers.dart';

class EJStatisticsPageVC extends StatefulWidget {
  const EJStatisticsPageVC({super.key});

  @override
  State<EJStatisticsPageVC> createState() => _EJStatisticsPageVCState();
}

class _EJStatisticsPageVCState extends State<EJStatisticsPageVC>
    with AutomaticKeepAliveClientMixin {
  ///保存选号到数据库
  MyTicketEntity ticketEntity = MyTicketEntity.instan();

  late List<Widget> _leftSideWiegets = []; //左侧日期view
  late var _rightSideWiegets = []; //右侧号码view

  double _leftWidth = 80; //左边宽度
  double _cellWidth = 25;
  double _cellHeight = 45;
  final ScrollController _titleController = ScrollController();
  final ScrollController _contentController = ScrollController();
  final ScrollController _leftListController = ScrollController();

  List<dynamic> _topTitleList = [];
  List _ballResults = [];
  List _draws_titles_left = []; //左边日期

  var _regularnumber = 0;
  var _extranumber = 0;
  var _chooseNumbers = [];

  _loadData() async {
    _draws_titles_left.clear();
    _ballResults.clear();

    _draws_titles_left.addAll(KaL_DataViewModels().EJ_draws_date);
    _draws_titles_left.addAll(KaL_DataViewModels().EJ_CalculateTitles);

    // _ballResults = KaL_DataViewModels().NL_ballsResults;
    _ballResults.addAll(KaL_DataViewModels().EJ_ballsResults);
    // _ballResults.add(KaL_DataViewModels().getAllCalculatedTitles());
    _ballResults.add(KaL_DataViewModels().EJ_CalculatedDrawings);
    _ballResults.add(KaL_DataViewModels().EJ_AverageSkipping);
    _ballResults.add(KaL_DataViewModels().EJ_MaximumSkipping);
    _ballResults.add(KaL_DataViewModels().EJ_MaximumConsecution);
    _ballResults.add(KaL_DataViewModels().EJ_ChooseNumbers);

    _topTitleList = KaL_DataViewModels().EJ_topTitles;
    await _loadLeftSideWidgets();
    await _loadRightSideWidgets();
    setState(() {
      //自动滑动到最底
      Future.delayed(const Duration(milliseconds: 500), () {
        _leftListController
            .jumpTo(_leftListController.position.maxScrollExtent);
      });
    });
  }

  //
  _loadLeftSideWidgets() {
    _leftSideWiegets.clear();
    for (var i = 0; i < _draws_titles_left.length; i++) {
      var element = _draws_titles_left[i];
      debugPrint('_draws_titles_left--$element');
      var isLastLine = i == _draws_titles_left.length - 1 ? true : false;
      // leftsideView(element, isLastLine);
      _leftSideWiegets.add(SizedBox(
        child: _leftsideView(element, isLastLine),
      ));
    }
    debugPrint('_leftSideWiegets--$_leftSideWiegets');
  }

  //
  _loadRightSideWidgets() {
    _rightSideWiegets.clear();
    for (var i = 0; i < _ballResults.length; i++) {
      var element = _ballResults[i];
      // debugPrint('_ballResults--$element');

      var isLastLine = i == _ballResults.length - 1 ? true : false;
      double lineH = 35;
      lineH = isLastLine ? lineH * 2 : lineH;

      Widget rowWidget = SizedBox(
        height: lineH,
        child: isLastLine
            ? SizedBox(
                height: 70,
                child: EJChooseNumber(
                  ///选号行
                  callback: (p0) {
                    debugPrint('$p0');
                    _chooseNumbers = p0;
                    _NL_configChooseNumbers();
                  },
                ),
              )
            : Row(
                children: _buildRightContent(i, isLastLine),
              ),
      );
      _rightSideWiegets.add(rowWidget);
    }
    debugPrint('_rightSideWiegets---$_rightSideWiegets');
  }

  _updateTitle() {
    if (_titleController.offset != _contentController.offset) {
      _titleController.jumpTo(_contentController.offset);
    }
  }

  _updateContent() {
    if (_contentController.offset != _titleController.offset) {
      _contentController.jumpTo(_titleController.offset);
    }
  }

  //save to checker
  _NL_saveTpChecker() async {
    if (_chooseNumbers.isEmpty ||
        _chooseNumbers.length < KaL_Config.numberTotles) {
      return;
    }
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });
    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "myTicket",
      "time": currentTimeMillis,
      "numbers": jsonEncode(_chooseNumbers),
    };

    ///保存选号
    // int save = await ticketEntity.insert(tickets);
    await ticketEntity.insert(tickets);

    Future.delayed(const Duration(seconds: 1), () {
      BotToast.closeAllLoading();
    });
  }

  //刷新选中号码数量
  _NL_configChooseNumbers() {
    _regularnumber = 0;
    _extranumber = 0;
    for (var element in _chooseNumbers) {
      bool isRegularnumber = element['regularnumber'] > 0 ? true : false;
      if (isRegularnumber) {
        _regularnumber += 1;
      } else {
        _extranumber += 1;
      }
    }
    setState(() {});
  }

  _leftsideView(String title, bool isLastLine) {
    Alignment alignment = Alignment.center;
    double viewH = _cellHeight - 10;
    double _titleOffset = 0;
    if (isLastLine) {
      alignment = Alignment.topCenter;
      viewH = viewH * 2;
      _titleOffset = 8.0;
    }
    return Container(
      // alignment: const Alignment(0, 0),
      alignment: alignment,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
          right: BorderSide(color: HexColor('#dddddd'), width: 1),
        ),
        // color: Colors.white,
      ),
      width: _cellWidth,
      height: viewH,
      child: Padding(
        padding: EdgeInsets.only(top: _titleOffset),
        child: Text(
          title,
          style: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _titleController.removeListener(_updateContent);
    _contentController.removeListener(_updateTitle);

    super.dispose();
  }

  _showLoading() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        title: 'loading...',
      );
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        title: 'loading...',
      );
    });
    Future.delayed(const Duration(milliseconds: 200), () {
      _loadData();
    });
    // _loadData();

    //监听自动滑动到最底，移除loading
    _leftListController.addListener(() {
      Future.delayed(const Duration(seconds: 1), () {
        BotToast.closeAllLoading();
      });
    });

    _titleController.addListener(_updateContent);
    _contentController.addListener(_updateTitle);
  }

  _buildTitleContainer(int i) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: HexColor('#dddddd'), width: 1),
          bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
          right: BorderSide(color: HexColor('#dddddd'), width: 1),
        ),
      ),
      alignment: Alignment.center,
      width: _cellWidth,
      height: _cellHeight,
      child: Text(
        _topTitleList[i],
        style: const TextStyle(
          color: Colors.black,
          fontWeight: FontWeight.w400,
          fontSize: 12,
        ),
      ),
    );
  }

  _buildRightTitle() {
    //顶部一行
    List<Widget> list = [];
    for (int i = 0; i < _topTitleList.length; i++) {
      list.add(_buildTitleContainer(i));
    }
    return list;
  }

  _buildRightContent(int index, bool isLastLine) {
    Alignment alignment = Alignment.center;
    double viewH = _cellHeight - 10;
    if (isLastLine) {
      alignment = Alignment.topCenter;
      viewH = viewH * 2;
    }
    //一行
    List<Widget> list = [];
    if (_ballResults.isNotEmpty) {
      var balls = _ballResults[index] ?? [];
      for (var element in balls) {
        ///有几多ball就有几多列
        var number = element['number'];
        var isRightNum = element['isRightNum'] != 0;
        var isRegular = element['regularnumber'] != 0;
        var hasborder = element['hasBorder'] > 0 ? true : false;
        // var hasborder = false;
        list.add(
          _numberView(
              number, hasborder, isRightNum, isRegular, viewH, alignment),
        );
      }
    }

    return list;
  }

  //格子+数字:hasBorder为是否有⭕️
  _numberView(
    String num,
    bool hasBorder, [
    bool? isRightNum = false,
    bool? isRegular = true,
    double? viewH = 45,
    Alignment? alignment = Alignment.center,
  ]) {
    double _topOffset = 0.0;
    if (alignment == Alignment.topCenter) {
      _topOffset = 10;
    }
    return Container(
      // margin: EdgeInsets.only(top: _topOff),
      alignment: alignment,
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
              right: BorderSide(color: HexColor('#dddddd'), width: 1))),
      width: _cellWidth,
      // height: _cellHeight - 10,
      height: viewH!,
      child: Padding(
        padding: EdgeInsets.only(top: _topOffset),
        child: number(num, hasBorder, isRightNum!, isRegular!),
      ),
      // child: number(num, hasBorder, isRightNum!, isRegular!),
    );
  }

  //数字
  Widget number(
    String num,
    bool hasBorder,
    bool isRightNum,
    bool isRegular,
  ) {
    double WH = 20;
    Color textColor = hasBorder ? KaL_Config.KaL_MainColor : Colors.black;
    double textSize = hasBorder ? 10 : 12;
    FontWeight weight = hasBorder ? FontWeight.w600 : FontWeight.w400;
    Color borderColor = KaL_Config.KaL_MainColor;
    Color bgColor = Colors.white;
    // if (hasBorder) {
    //   if (isRegular) {
    //     bgColor = isRightNum ? EJ_Config.EJ_MainColor : bgColor;
    //     textColor = isRightNum ? Colors.white : EJ_Config.EJ_MainColor;
    //   } else {
    //     bgColor = isRightNum ? HexColor('#ffab2d') : bgColor;
    //     borderColor = HexColor('#ffab2d');
    //     textColor = isRightNum ? Colors.white : HexColor('#ffab2d');
    //   }
    // }
    if (isRegular) {
      bgColor = isRightNum ? KaL_Config.KaL_MainColor : bgColor;
      textColor = isRightNum ? Colors.white : HexColor('#999999');
    } else {
      bgColor = isRightNum ? KaL_Config.KaL_MainColor : bgColor;
      borderColor = KaL_Config.KaL_MainColor;
      textColor = isRightNum ? Colors.white : HexColor('#999999');
    }
    if (!hasBorder) {
      //
      textColor = Colors.black;
    }

    return Container(
      width: WH,
      height: WH,
      alignment: Alignment.center,
      decoration: isRightNum
          ? BoxDecoration(
              color: bgColor,
              border: Border.all(width: 1, color: borderColor),
              borderRadius: BorderRadius.all(Radius.circular(WH * 0.5)),
            )
          : null,
      child: Text(
        num,
        style: TextStyle(
          fontWeight: weight,
          fontSize: textSize,
          color: textColor,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        // title: const Text(
        //   'Statistics',
        //   style: TextStyle(
        //     fontWeight: FontWeight.w600,
        //     fontSize: 18,
        //   ),
        // ),
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: Colors.white,
        foregroundColor: KaL_Config.KaL_MainColor,
        centerTitle: true,
      ),
      body: Container(
          color: KaL_Config.KaL_pageBgColor,
          child: _draws_titles_left.isNotEmpty
              ? Column(
                  children: [
                    Expanded(
                        child: Column(
                      children: [
                        Row(
                          children: [
                            Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                  top: BorderSide(
                                      color: HexColor('#dddddd'), width: 1),
                                  bottom: BorderSide(
                                      color: HexColor('#dddddd'), width: 1),
                                  right: BorderSide(
                                      color: HexColor('#dddddd'), width: 1),
                                ),
                              ),
                              width: _leftWidth,
                              height: _cellHeight,
                              alignment: Alignment.center,
                              child: const Text('Draws',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.w400,
                                    fontSize: 12,
                                  )),
                            ),
                            Expanded(
                                child: SizedBox(
                              width: _topTitleList.length * _cellWidth,
                              child: SingleChildScrollView(
                                physics: ClampingScrollPhysics(),
                                controller: _titleController,
                                scrollDirection: Axis.horizontal,
                                child: Row(
                                  children: _buildRightTitle(),
                                ),
                              ),
                            ))
                          ],
                        ),
                        Expanded(
                          child: SingleChildScrollView(
                            // physics: ClampingScrollPhysics(),
                            controller: _leftListController,
                            child: Column(
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      color: Colors.white,
                                      width: _leftWidth,

                                      ///左侧list
                                      child: ListView.builder(
                                        shrinkWrap: true,
                                        physics:
                                            const NeverScrollableScrollPhysics(),
                                        itemBuilder: (context, index) {
                                          Widget item = _leftSideWiegets[index];
                                          return item;
                                        },
                                        itemCount: _draws_titles_left.length,
                                      ),
                                    ),
                                    Expanded(
                                        child: SingleChildScrollView(
                                      physics: ClampingScrollPhysics(),
                                      controller: _contentController,
                                      scrollDirection: Axis.horizontal,
                                      child: Container(
                                        width:
                                            _topTitleList.length * _cellWidth,
                                        child: ListView.builder(
                                          //
                                          itemCount:
                                              _rightSideWiegets.length, //行数
                                          shrinkWrap: true,
                                          physics:
                                              const NeverScrollableScrollPhysics(),
                                          itemBuilder: (context, index) {
                                            Widget item =
                                                _rightSideWiegets[index];
                                            return item;
                                          },
                                        ),
                                        // ),
                                      ),
                                    )),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    )),
                    bottomView(),
                  ],
                )
              : null
          // : Container(
          //     child: Center(
          //       child: Text('loading...'),
          //     ),
          //   ),
          ),
    );
  }

  Future<void> _refreshData() async {
    setState(() {
      // _isLoading = true;
    });

    // 模拟网络请求
    await Future.delayed(Duration(seconds: 2));

    // 重新加载数据
    setState(() {
      // _data = List.generate(20, (index) => 'Item ${index + 1}');
      // _isLoading = false;
    });
  }

  Widget bottomView() {
    var regularNumCount = KaL_Config.regularNumCount;
    return Container(
      height: 45,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Text(
            'Choose $regularNumCount numbers to save($_regularnumber/$regularNumCount)',
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w400,
            ),
          ),
          const Spacer(),
          OutlinedButton(
            onPressed: () {
              debugPrint('Save to Checker');
              _NL_saveTpChecker();
            },
            style: ButtonStyle(
                backgroundColor:
                    WidgetStatePropertyAll(KaL_Config.KaL_MainColor),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                side: WidgetStateProperty.all(
                    //边框
                    BorderSide(
                  color: KaL_Config.KaL_MainColor, //颜色
                  width: 1.0, //宽度
                )),
                minimumSize: const MaterialStatePropertyAll(Size(40, 35))),
            child: const Text(
              "Save to Checker",
              style: TextStyle(fontWeight: FontWeight.w400, fontSize: 13),
            ),
          ),
          SizedBox(width: 15),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
